package com.xiaojie.edi.mybatisplus;

import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.xiaojie.edi.mybatisplus.listener.DataEDIApplicationRunner;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author liaoke
 * @date 2021/12/16
 **/
@Component
public class FieldTypeHandleService {


    /**
     * 导出处理字段类型
     *
     * @param tableName 表名
     * @param maps      数据
     */
    public void exportHandleDataByFieldType(String tableName, List<Map> maps) {
        // 获取表名对应的反射类名
        TableInfo tableInfoFormMybatis = DataEDIApplicationRunner.TABLE_INFO_MAP.get(tableName);
        if (tableInfoFormMybatis != null) {
            //获取存储二进制数据的字段
            List<String> bFieldNames = tableInfoFormMybatis.getFieldList().stream()
                    .filter(o -> isByteArray(o.getPropertyType()))
                    .map(TableFieldInfo::getColumn)
                    .collect(Collectors.toList());

            for (String bFieldName : bFieldNames) {
                for (Map row : maps) {
                    Object d = row.get(bFieldName);
                    //仅当为字节类型时进行处理
                    if (d instanceof byte[]) {
                        row.put(bFieldName, new String((byte[]) d, StandardCharsets.UTF_8));
                    }
                }
            }
        }
    }


    public Object importHandleDataByFieldType(Object value, Class propertyType) {
        if (value == null) {
            value = "null";
        } else {
            if (value instanceof String) {
                //lk新增 处理特殊字符
                value = "'" + ((String) value).replaceAll("\\\\", "\\\\\\\\")
                        .replaceAll("'", "\\\\'") + "'";
            }
            if (isByteArray(propertyType)) {
                //是字节数组
                //存储二进制数据字段
                value = "CONVERT(" + value + ",BINARY )";
            }
        }
        return value;
    }

    private boolean isByteArray(Class c) {
        return c != null && c.isArray() && c.getComponentType() == byte.class;
    }

}
